#include <kernel/bus.h>
#include <kernel/initcall.h>
#include <kernel/syslog.h>
#include <drivers/platform.h>
#include <string.h>


/**
 * @brief platform bus probe, it will be called when driver and device matched
 * @param dev device
 * @return 0 on success, -1 on failure
 */
static int platform_bus_probe(struct device *dev)
{
    struct platform_device *pdev = to_platform_device(dev);
    struct platform_driver *pdrv = to_platform_driver(dev->driver);

    if(pdrv && pdrv->probe) {
        SYSLOG_INFO("probe: %s", dev->compatible);
        return pdrv->probe(pdev);
    }

    return 0;
}


/**
 * @brief platform bus remove
 * @param dev device
 * @return none
 */
static void platform_bus_remove(struct device *dev)
{
    struct platform_device *pdev = to_platform_device(dev);
    struct platform_driver *pdrv = to_platform_driver(dev->driver);

    if(pdrv->remove) {
        pdrv->remove(pdev);
    }
}


struct bus_type platform_bus = {
    .name = "platform",
    .match = bus_simple_match,
    .probe = platform_bus_probe,
    .remove = platform_bus_remove,
};


/**
 * @brief platform bus register
 * @return 0 on success, -1 on failure
 * @note this function must be called when system is initializing, before any platform device or drivers is registered
 */
int platform_bus_register(void)
{
    return bus_register(&platform_bus);
}
